import { defineStore } from 'pinia'

export const useRfqStore = defineStore('rfq', () => {
// 表格数据
let nextId = 1


// 创建空行数据
const createEmptyRow = () => ({
  id: nextId++,
  partNo: '',
  manufacturer: '',
  package: '',
  datecode: '',
  quantity: 1,
  targetPrice: 1,
  remarks: '',
  showRemarks: false
})

const tableData = ref([
  createEmptyRow(),
  createEmptyRow(),
  createEmptyRow()
])

// 添加新行
const addRow = () => {
  tableData.value.push(createEmptyRow())
}

// 删除指定行
const removeRow = (index) => {
  tableData.value.splice(index, 1)
  // 如果删除完所有行，自动添加一个空行
  if (tableData.value.length === 0) {
    addRow()
  }
}

// 删除所有行
const removeAll = () => {
  tableData.value = [createEmptyRow()]
}

// 切换备注显示状态
const toggleRemarks = (index) => {
  tableData.value[index].showRemarks = !tableData.value[index].showRemarks
}

// 找到第一个空数据行然后添加进去数据,如果都有数据就新建一个空行
const findEmptyRow = () => {
  for (let i = 0; i < tableData.value.length; i++) {
    console.log(tableData.value[i])
    if (tableData.value[i].partNo === '' && tableData.value[i].manufacturer === '' && tableData.value[i].package === '' && tableData.value[i].datecode === '' && tableData.value[i].quantity === 1 && tableData.value[i].targetPrice === 1 && tableData.value[i].remarks === '') {
      return tableData.value[i]
    }
  }
  addRow()
  return tableData.value[tableData.value.length - 1]
}

// 给表格数据写入数据
const setData = (data) => {
  const tableDataItem = findEmptyRow()
  tableDataItem.partNo = data.PartNo
  tableDataItem.manufacturer = data.MFG
  tableDataItem.quantity = data.Quantity
}

return {
  tableData,
  addRow,
  removeRow,
  removeAll,
  toggleRemarks,
  setData
}

})